package com.课上案例练习.线程.线程操作;

/**
 * 1.线程加入
 * 当指定线程调用 join()时，线程的执行权会交给该线程，
 * 并且当前线程必须等到该线程执行完毕之后才能执行，
 * 但有可能被其他线程抢去执行权
 */
public class Test2 {
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            for (int i = 0; i <= 10; i++) {
                System.out.println("i："+i+"当前线程名称："+Thread.currentThread().getName()+",线程id:"+Thread.currentThread().getId());
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"线程A");

        Thread t2 =new Thread(()->{
            for (int j = 0; j <= 20; j++) {
                System.out.println("j："+j+"当前线程名称："+Thread.currentThread().getName()+",线程id:"+Thread.currentThread().getId());
                if(j==10){
                    try {
                        t1.join(); // 等待线程A执行完毕
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                try {
                    Thread.sleep(40);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"线程B");

        t1.start();
        t2.start();
    }
}
